<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * @property int $id
 * @property int $goods_id
 * @property int $user_id
 * @property string $date
 * @property string $goods_action
 * @property int $total_num
 * @property int $stock_total_num
 * @property int $stock_use_num
 * @property int $stock_leave_num
 * @property int $stock_bad_num
 * @property string $updated_at
 * @property string $created_at
 */
class GoodsStockHis extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'goods_stock_history';

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * @var array
     */
    protected $fillable = ['goods_id', 'user_id', 'date', 'goods_action', 'total_num','stock_total_num', 'stock_use_num', 'stock_leave_num', 'stock_bad_num', 'updated_at', 'created_at'];


    /**
     * 商品库存操作记录表
     * @param $user_id
     * @param $goods_id
     * @param $goods_action
     * @param $total_num
     * @return bool
     */
    public static function log($user_id,$goods_id,$goods_action,$total_num)
    {
        $goods_stock = GoodsStock::where("goods_id",$goods_id)->first();
        $goods_stock_his = new GoodsStockHis();
        $goods_stock_his->goods_id = $goods_id;
        $goods_stock_his->user_id = $user_id;
        $goods_stock_his->date = date("Y-m-d H:i:s");
        $goods_stock_his->goods_action = $goods_action;
        $goods_stock_his->total_num = $total_num;
        $goods_stock_his->stock_total_num = $goods_stock->total_num;
        $goods_stock_his->stock_use_num = $goods_stock->use_num;
        $goods_stock_his->stock_leave_num = $goods_stock->leave_num;
        $goods_stock_his->stock_bad_num = $goods_stock->bad_num;
        $goods_stock_his->updated_at = date("Y-m-d H:i:s");
        $goods_stock_his->created_at = date("Y-m-d H:i:s");
        return $goods_stock_his->save();
    }

    public function userInfo(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne('App\Models\Users', "id", "user_id")->select("id",'nickname');
    }

    public function goodsInfo(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne('App\Models\Goods', "id", "goods_id")->select("id",'name');
    }

    public static function receivedToday($goodId, $userId)
    {
        $date = date('Y-m-d 00:00:00');
        return (int)DB::table('goods_stock_history')
            ->where('date', '>=', $date)
            ->where([
                ['goods_id', $goodId],
                ['user_id', $userId],
                ['goods_action', '领用'],
            ])->sum('total_num');
    }


}
